package edu.ycu.aladdin.web.controller.crawler;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.ycu.aladdin.collector.api.CrawlerConfigService;
import edu.ycu.aladdin.collector.api.entity.CrawlerConfig;
import edu.ycu.aladdin.web.api.crawler.CrawlerConfigAPI;
import edu.ycu.aladdin.web.common.RestResponse;
import edu.ycu.aladdin.web.controller.AbsController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
public class CrawlerConfigController extends AbsController implements CrawlerConfigAPI {


    @Reference(lazy = true, check = false)
    private CrawlerConfigService crawlerConfigService;

    @Override
    @RequestMapping(method = RequestMethod.POST)
    public RestResponse addConfig(CrawlerConfig config) {

        log.debug("add crawler config :{}", config);

        crawlerConfigService.addConfig(config);
        return RestResponse.successResponse(null);
    }

    @Override
    public RestResponse addConfigByJson(@RequestBody CrawlerConfig config) {

        log.debug("add crawler config :{}", config);

        crawlerConfigService.addConfig(config);
        return RestResponse.successResponse(null);
    }

    @Override
    public RestResponse getAll(Boolean withId) {

        Object res;
        if (withId == null || withId.equals(Boolean.FALSE)) {
            res = crawlerConfigService.getAllConfig();
        } else {
            Map<Object, Object> allWithId = crawlerConfigService.allWithId();
            List<JSONObject> jsonObjects = new LinkedList<>();
            for (Object key : allWithId.keySet()) {
                Object value = allWithId.get(key);
                JSONObject o = (JSONObject) JSON.toJSON(value);
                o.put("id", key);
                jsonObjects.add(o);
            }

            res = jsonObjects;
        }
        return RestResponse.successResponse(res);
    }

    /**
     * 获取一个默认配置
     *
     * @return
     */
    @Override
    public RestResponse getDefaultConfig() {

        CrawlerConfig crawlerConfig = new CrawlerConfig();
        crawlerConfig.setDomain("");
        crawlerConfig.setUserAgent("");
        crawlerConfig.setCharset("");
        return RestResponse.successResponse(crawlerConfig);
    }


    @Override
    public RestResponse delConfig(String id, CrawlerConfig config) {

        if (id == null) {
            if (config == null) {
                return new RestResponse(RestResponse.Type.PARAM_INVALID, null);
            }
            crawlerConfigService.delConfig(config);
        } else {
            crawlerConfigService.delConfig(id);
        }
        return RestResponse.successResponse(null);
    }
}
